<?php
/*
 * Created on 2012-5-8
 * @iChying
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

 include_once("compress.php");

 class UnicodeDecompress {
  	public $decode_index_table;
  	private $decompress_table;

  	public function __construct() {
  		$this->initialize();
  	}

  	private function initialize() {
  		$this->generateDecodeTable();
  		$this->generateDecompressTable();
  	}

  	private function generateDecodeTable() {
  		$this->decode_index_table = array();

  		// 0-9
  		for ($i = 0; $i < 10; ++$i) {
  			$this->decode_index_table[] = chr(ord('0') + $i);
  		}

  		// a-f
  		for ($i = 0; $i < 6; ++$i) {
  			$this->decode_index_table[] = chr(ord('a') + $i);
  		}
  	}

  	private function generateDecompressTable() {
		function gen_dearray($value) {
			$bit_val1 = $value;
			$bit_val2 = ($value & 0x3c) >> 2;
			$bit_val3 = ($value & 0x03) << 2;
			$bit_val4 = ($value & 0x30) >> 4;
			$bit_val5 = $value & 0x0f;
			$bit_val6 = ($value & 0x3c) >> 2;

			return array($bit_val1, $bit_val2, $bit_val3, $bit_val4, $bit_val5, $bit_val6);
		}

		$this->decompress_table = array();

		// A-Z
		for ($i = 0; $i <= 25; ++$i) {
 			$this->decompress_table[chr(ord('A') + $i)] = gen_dearray($i);
 		}

		// a-z
 		for ($i = 26, $j = 0; $i <= 51; ++$i, ++$j) {
 			$this->decompress_table[chr(ord('a') + $j)] = gen_dearray($i);
 		}

		// 0-9
 		for ($i = 52, $j = 0; $i <= 61; ++$i, ++$j) {
 			$this->decompress_table[chr(ord('0') + $j)] = gen_dearray($i);
 		}

 		// +
 		$this->decompress_table['+'] = gen_dearray(62);

		// /
 		$this->decompress_table['/'] = gen_dearray(63);
  	}

  	public function decompressUnicode($compressStr) {
  		$unicodeCodePoint = '';
  		$compressStrLength = strlen($compressStr);

		for ($i = 0; $i < $compressStrLength; $i += 3) {
			$ch1 = $compressStr{$i};
			$ch2 = $compressStr{($i + 1)};
			$ch3 = $compressStr{($i + 2)};

			$baseValue2 = $this->decompress_table[$ch2][0];
			$baseValue3 = $this->decompress_table[$ch3][0];

			if ($baseValue3 & 0x1) {
				$baseValue2 = $baseValue2 | 0x08;
				$ch2 = UnicodeCompress::$encode_index_table[$baseValue2];
			}

			$decodeIndex1 = $this->decompress_table[$ch1][1];
			$decodeIndex2 = ($this->decompress_table[$ch1][2]) | ($this->decompress_table[$ch2][3]);
			$decodeIndex3 = $this->decompress_table[$ch2][4];
			$decodeIndex4 = $this->decompress_table[$ch3][5];

			$unicodeCodePoint .= $this->decode_index_table[$decodeIndex1];
			$unicodeCodePoint .= $this->decode_index_table[$decodeIndex2];
			$unicodeCodePoint .= $this->decode_index_table[$decodeIndex3];
			$unicodeCodePoint .= $this->decode_index_table[$decodeIndex4];
		}

		return $unicodeCodePoint;

  	}
 }

?>